package com.chensi.handler;

import java.io.IOException;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.chensi.common.Constants;
import com.chensi.common.Global;
import com.chensi.common.LoginUser;
import com.chensi.socket.model.MessageReceive;

public class MySessionListener implements SessionListener {

	private static final Logger logger = LoggerFactory.getLogger(MySessionListener.class);

	/**
	 * 会话过期，注销socket
	 */
	@Override
	public void onExpiration(Session session) {
		logger.info("会话{}已过期", session.getId());
		LoginUser loginUser = (LoginUser) session.getAttribute(Constants.LOGIN_USER);
		MessageReceive receive = new MessageReceive();
		receive.setEmit(Constants.SOCKET_OVERTIME);
		if (Global.userSocketSessionMap.size() > 0) {
			WebSocketSession sessionTarget = Global.userSocketSessionMap.get(loginUser.getId());
			if (sessionTarget != null && sessionTarget.isOpen()) {
				try {
					sessionTarget.sendMessage(new TextMessage(Global.gson.toJson(receive)));
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// 移除socketId
			Global.userSocketSessionMap.remove(loginUser.getId());
		}

	}

	@Override
	public void onStart(Session session) {
		logger.info("会话{}已开始", session.getId());
	}

	@Override
	public void onStop(Session session) {
		logger.info("会话{}已停止", session.getId());
	}

}
